package com.kilomob.grady.handler.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kilomob.grady.client.DefaultFuture;
import com.kilomob.grady.client.netty.NettyChannelFactory;
import com.kilomob.grady.model.Response;

/**
 * 
 * 消息发送处理类
 *   
 * @author zhouzhixiang  
 * @date 2017年1月2日
 * @since 1.0
 */
public class MessageSendHandler extends ChannelInboundHandlerAdapter {
    private static Logger LOGGER = LoggerFactory.getLogger(MessageSendHandler.class);
    
    volatile private Channel channel;
    private SocketAddress remoteAddr;
    
    private String id;

    public MessageSendHandler(String id){
        this.id = id;
    }
    
    public Channel getChannel() {
        return channel;
    }

    public SocketAddress getRemoteAddr() {
        return remoteAddr;
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel();
        LOGGER.info("Connects with {}.", ch);
        super.channelActive(ctx);
        this.remoteAddr = this.channel.remoteAddress();
    }
    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel();
        NettyChannelFactory.getChannels(id).remove(ch);
        ctx.fireChannelActive();
    }
    
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        this.channel = ctx.channel();
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Response response = (Response) msg;
        DefaultFuture.received(ctx.channel(), response);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
        LOGGER.error("server may be error:",cause);
    }

    public void close() {
        channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
    
}
